package controller.wetch;


import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import util.ConstantWeChat;
import util.HttpRequestUtil;
import util.MessageUtil;
import util.SignUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 * 微信接入
 * Created by bowen on 2016/7/28.
 */
@Controller
@RequestMapping(value = "/weChat")
public class WeChatInletController {

    private static final Logger logger = LoggerFactory.getLogger(WeChatInletController.class);



    /**

     *

     * 微信接入接口

     * @author songbaoming

     * @date 2017年4月27日

     * @param signature  微信加密签名

     * @param timestamp	  时间戳

     * @param nonce		随机数

     * @param echostr	随机字符串

     * @param response

     * @throws IOException

     */
    @RequestMapping(value = { "signature" }, method = RequestMethod.GET)
    public void signature(@RequestParam(value = "signature", required = true) String signature,
                          @RequestParam(value = "timestamp", required = true) String timestamp,
                          @RequestParam(value = "nonce", required = true) String nonce,
                          @RequestParam(value = "echostr", required = true) String echostr, HttpServletResponse response)
            throws IOException {
        PrintWriter out = response.getWriter();
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败

        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
            System.out.println("微信服务验证成功！");
        }
        out.close();
        out = null;
    }


    @RequestMapping(value = { "signature" }, method = RequestMethod.POST)
    public  void processRequest(HttpServletResponse response,HttpServletRequest request) throws Exception {
        System.out.println("进入公众号事件方法");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String respMessage = null;

        try {
            // xml请求解析

            Map<String, String> requestMap = MessageUtil.parseXml(request);

            // 发送方帐号（open_id）

            String fromUserName = requestMap.get("FromUserName");
            System.out.println("用户的opendid"+fromUserName);
            // 公众帐号

            String toUserName = requestMap.get("ToUserName");
            // 消息类型

            String msgType = requestMap.get("MsgType");

            System.out.println("msgType------------------"+msgType);
            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setCreateTime(new Date().getTime());
            textMessage.setMsgType(msgType);
            textMessage.setFuncFlag(0);
            String respContent = "";
            // 文本消息
            textMessage.setContent("进去了。");
            respMessage = MessageUtil.textMessageToXml(textMessage);
            if (msgType.equals(ConstantWeChat.REQ_MESSAGE_TYPE_TEXT)) {
                // 接收用户发送的文本消息内容

                String content = requestMap.get("Content");
                System.out.println("content--------------"+content);
                // 创建图文消息

                NewsMessage newsMessage = new NewsMessage();
                newsMessage.setToUserName(fromUserName);
                newsMessage.setFromUserName(toUserName);
                newsMessage.setCreateTime(new Date().getTime());
                newsMessage.setMsgType(ConstantWeChat.RESP_MESSAGE_TYPE_NEWS);
                newsMessage.setFuncFlag(0);


                List<Article> articleList = new ArrayList<Article>();
                Article article = new Article();

                article.setTitle("微信公众帐号开发教程Java版");

                article.setDescription("柳峰，80后，微信公众帐号开发经验4个月。为帮助初学者入门，特推出此系列教程，也希望借此机会认识更多同行！");

                article.setPicUrl("http://0.xiaoqrobot.duapp.com/images/avatar_liufeng.jpg");

                article.setUrl("http://blog.csdn.net/lyq8479");

                articleList.add(article);

                newsMessage.setArticleCount(articleList.size());

                newsMessage.setArticles(articleList);

                respContent = "你输入了"+content;

                // 单图文消息

	              /*  if ("1".equals(content)) {

	                	 System.out.println("你进了1这个--------------");

	                	respContent = "你输入了1";

	                }else if ("2".equals(content)) {

	                	respContent = "你输入了2";

	                }else

	                // 多图文消息

	                 if ("3".equals(content)) {

	                	respContent = "你输入了3";

	                }else{

	                	respContent = "无效输入";

	                }*/
	                /*respMessage = MessageUtil.newsMessageToXml(newsMessage);*/
                //事件处理开始

            } else if (msgType.equals(ConstantWeChat.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型

                String eventType = requestMap.get("Event");
                //关注

                if (eventType.equals(ConstantWeChat.EVENT_TYPE_SUBSCRIBE)) {
                    System.out.println("进入公众号关注事件————————————————————————");
                 /*   Object token = CacheMap.getInstance().get("accesstoken");
                    HttpRequestUtil.sendClientRequest("getPlanToday", null);
                    System.out.println("tokend值为-----------------"+token);
                    System.out.println("fromUserName值为---------------"+fromUserName);
                    JSONObject jsonObject = HttpRequestUtils.httpGet("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid="+fromUserName+"&lang=zh_CN");
                    System.out.println("获取的用户基本信息"+JSONObject.toJSONString(jsonObject));
                    if(jsonObject.containsKey("errcode")){
                        System.out.println("获取用户信息失败---------------错误码为"+jsonObject.getInteger("errcode"));
                    }else{

                    }*/

                /*    FollowReply followReply = new FollowReply();
                    List<FollowReply> fllowReplyList = followReplyServiceImpl.selectList(followReply);*/
               /*     if(fllowReplyList.size() > 0 ){
                        FollowReply fr = fllowReplyList.get(0);
                        if("1".equals(fr.getType())){
                            NewsMessage newsMessage = new NewsMessage();
                            newsMessage.setToUserName(fromUserName);
                            newsMessage.setFromUserName(toUserName);
                            newsMessage.setCreateTime(new Date().getTime());
                            newsMessage.setMsgType(ConstantWeChat.RESP_MESSAGE_TYPE_NEWS);
                            newsMessage.setFuncFlag(0);

                          *//*  List<Article> articleList = new ArrayList<Article>();
                            Article article = new Article();

                            article.setTitle(fr.getTitle());

                            article.setDescription(fr.getContent());
                            String prcurl = File.separator+"upload"+File.separator+fr.getId()+File.separator+fr.getPicurl();
                            article.setPicUrl(domainname+prcurl);
                            article.setUrl("");
                            articleList.add(article);*//*

                            newsMessage.setArticleCount(articleList.size());
                            newsMessage.setArticles(articleList);

                            respMessage = MessageUtil.newsMessageToXml(newsMessage);
                        }else{
                          *//*  TextMessage textMessage = new TextMessage();
                            textMessage.setToUserName(fromUserName);
                            textMessage.setFromUserName(toUserName);
                            textMessage.setCreateTime(new Date().getTime());
                            textMessage.setMsgType(ConstantWeChat.RESP_MESSAGE_TYPE_TEXT);
                            textMessage.setFuncFlag(0);
                            textMessage.setContent(fr.getContent());
                            respMessage = MessageUtil.textMessageToXml(textMessage);*//*
                        }
                    }*/

                } else if (eventType.equals(ConstantWeChat.EVENT_TYPE_UNSUBSCRIBE)) {
                    /*// 取消关注,用户接受不到我们发送的消息了，可以在这里记录用户取消关注的日志信息

                    WeixinUserInfo weixinUserInfo = weixinUserInfoServiceImpl.selectByOpenId(fromUserName);
                    if(weixinUserInfo!=null){
                        weixinUserInfo.setSubscribe(0);
                        weixinUserInfoServiceImpl.update(weixinUserInfo);
                    }*/

                }  else if (eventType.equals(ConstantWeChat.EVENT_TYPE_CLICK)) {

                    // 事件KEY值，与创建自定义菜单时指定的KEY值对应

                    String eventKey = requestMap.get("EventKey");

                    // 自定义菜单点击事件

                    if (eventKey.equals("11")) {
                        respContent = "天气预报菜单项被点击！";
                    } else if (eventKey.equals("12")) {
                        respContent = "公交查询菜单项被点击！";
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("返回给微信消息-------------------------"+respMessage);
        out.print(respMessage);
        out.flush();
    }



}
